<?php

$action = filter_input(INPUT_GET, 'action');
$func = 'action_'.($action && preg_match('/^\w{1,32}$/', $action) ? $action : 'default');
if (!function_exists($func)) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied!');
}
$func();
exit;

// ===== actions ===== //

function action_direct() {
    write_log('direct request.');
    echo 'ok';
}

function action_simple() {
    enable_cors();
    write_log('simple request.');
    echo 'ok';
}

function action_complex() {
    enable_cors(['header' => 'MyHeader']);
    write_log('complex request.');
    echo 'ok';
}

function action_credential() {
    enable_cors(['credential' => true]);
    write_log('credential request.');
    $loop = filter_input(INPUT_COOKIE, 'session-loop');
    setcookie('session-loop', $loop ? intval($loop) + 1 : 1);
    echo 'ok';
}

function action_log() {
    enable_cors();
    $logs = get_logs();
    echo implode("\n", $logs);
}

// ===== libs ===== //

function enable_cors($option = []) {
    static $allowOrigins = ['http://127.0.0.1:8555'];
    // 允许的来源域名
    $origin = filter_input(INPUT_SERVER, 'HTTP_ORIGIN');
    if (!$origin || !in_array($origin, $allowOrigins)) {
        return;
    }
    // 允许的 header
    $headers = ['x-requested-with', 'content-type'];
    if ($option && !empty($option['header'])) {
        header('Access-Control-Allow-Credentials:true');
        $headers = array_merge($headers, (array)$option['header']);
    }
    header('Access-Control-Allow-Origin:'.$origin);
    header('Access-Control-Allow-Methods:POST,GET,PUT');
    header('Access-Control-Allow-Headers:'.implode(',', $headers));
    // 开启认证（允许 cookie 传递）
    if ($option && !empty($option['credential'])) {
        header('Access-Control-Allow-Credentials:true');
    }
    if (strtoupper(filter_input(INPUT_SERVER, 'REQUEST_METHOD')) === 'OPTIONS'){
        write_log('METHOD: OPTIONS');
        // 注意: 这里需要终止后续运行！
//        exit;
    }
}

function _get_logfile() {
    $file = dirname(__FILE__).'/tmp_logs.json';
    if (!file_exists($file)) {
        touch($file);
    }
    return $file;
}
function write_log($log) {
    $file = _get_logfile();
    $data = json_decode(file_get_contents($file), true);
    if (!$data) {
        $data = [];
    }
    $context = [
        'id' => filter_input(INPUT_GET, 'id'),
        'action' => filter_input(INPUT_GET, 'action'),
        'body' => file_get_contents('php://input'),
        'cookie(session-loop)' => filter_input(INPUT_COOKIE, 'session-loop')
    ];
    $content = date('[Y-m-d H:i:s] ')
        .$log
        .' | (context=>)'. json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ;
    array_unshift($data, $content);
    if (count($data) > 20) {
        $data = array_slice($data, 0, 20);
    }
    file_put_contents($file, json_encode($data));
    return true;
}
function get_logs() {
    $file = _get_logfile();
    $data = json_decode(file_get_contents($file), true);
    return $data ? $data : [];
}